<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" th:replace="~{common/base :: layout(~{::title}, ~{::content}, ~{::style}, ~{::script})}">
<head>
    <title>我的购物车 - 优选商城</title>
    <style>
        .cart-item {
            padding: 15px 0;
            border-bottom: 1px solid #eee;
        }
        .cart-item:last-child {
            border-bottom: none;
        }
        .cart-item img {
            width: 80px;
            height: 80px;
            object-fit: cover;
        }
        .quantity-control {
            width: 120px;
        }
        .cart-summary {
            background-color: #f8f9fa;
            padding: 20px;
            border-radius: 5px;
        }
        .empty-cart {
            text-align: center;
            padding: 50px 0;
        }
        .empty-cart i {
            font-size: 4rem;
            color: #ccc;
        }
    </style>
</head>
<body>
    <div th:fragment="content">
        <div class="container my-4">
            <h2 class="mb-4">我的购物车</h2>
            
            <!-- 购物车内容 -->
            <div class="row" id="cartContainer">
                <div class="col-md-9" id="cartItems">
                    <div class="card">
                        <div class="card-header bg-white">
                            <div class="d-flex align-items-center">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" id="selectAll" checked>
                                    <label class="form-check-label" for="selectAll">全选</label>
                                </div>
                                <div class="ms-4">商品信息</div>
                                <div class="ms-auto">
                                    <button class="btn btn-sm btn-outline-danger" onclick="deleteSelected()">
                                        <i class="bi bi-trash"></i> 删除选中
                                    </button>
                                </div>
                            </div>
                        </div>
                        <div class="card-body">
                            <div class="empty-cart" id="emptyCart" style="display: none;">
                                <i class="bi bi-cart-x"></i>
                                <h5 class="mt-3">您的购物车还是空的</h5>
                                <p class="text-muted">快去添加商品吧！</p>
                                <a href="/" class="btn btn-primary mt-3">去购物</a>
                            </div>
                            <div id="cartItemsList"></div>
                        </div>
                    </div>
                </div>
                
                <div class="col-md-3">
                    <div class="card cart-summary">
                        <div class="card-body">
                            <h5 class="card-title">结算信息</h5>
                            <div class="d-flex justify-content-between mb-2">
                                <span>已选商品:</span>
                                <span id="selectedCount">0</span>
                            </div>
                            <div class="d-flex justify-content-between mb-3">
                                <span>合计:</span>
                                <span class="text-danger fw-bold">¥<span id="totalPrice">0.00</span></span>
                            </div>
                            <button class="btn btn-danger w-100" id="checkoutBtn" onclick="checkout()" disabled>
                                结算
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script th:fragment="script">
        let cartData = [];
        
        // 页面加载完成后获取购物车数据
        $(document).ready(function() {
            loadCartItems();
            
            // 全选/取消全选
            $('#selectAll').change(function() {
                const checked = $(this).prop('checked');
                updateAllItemsChecked(checked);
            });
        });
        
        // 加载购物车商品
        function loadCartItems() {
            $.ajax({
                url: '/cart/list',
                type: 'GET',
                success: function(res) {
                    if (res.code === 0) {
                        renderCart(res.data);
                    } else {
                        showError(res.msg || '获取购物车失败');
                    }
                },
                error: function() {
                    showError('获取购物车失败，请重试');
                }
            });
        }
        
        // 渲染购物车数据
        function renderCart(data) {
            console.log("购物车数据:", data);
            cartData = data || [];
            renderCartItems();
            updateCartSummary();
        }
        
        // 渲染购物车列表
        function renderCartItems() {
            const cartItemsList = $('#cartItemsList');
            cartItemsList.empty();
            
            if (cartData.length === 0) {
                $('#emptyCart').show();
                $('#checkoutBtn').prop('disabled', true);
                return;
            }
            
            $('#emptyCart').hide();
            
            cartData.forEach(function(item) {
                const product = item.product;
                if (!product) return;
                
                const cartItemHtml = `
                    <div class="cart-item" data-id="${item.id}">
                        <div class="row align-items-center">
                            <div class="col-auto">
                                <div class="form-check">
                                    <input class="form-check-input item-checkbox" type="checkbox" 
                                           ${item.checked === 1 ? 'checked' : ''} 
                                           onchange="updateItemChecked(${item.id}, this.checked)">
                                </div>
                            </div>
                            <div class="col-auto">
                                <img src="${product.mainImage}" class="img-thumbnail" alt="${product.name}">
                            </div>
                            <div class="col">
                                <h6>${product.name}</h6>
                                <div class="text-muted small">${product.subtitle || ''}</div>
                                <div class="mt-2">
                                    <span class="text-danger">¥${product.price.toFixed(2)}</span>
                                </div>
                            </div>
                            <div class="col-auto">
                                <div class="input-group quantity-control">
                                    <button type="button" class="btn btn-outline-secondary" 
                                            onclick="decreaseQuantity(${item.id})">-</button>
                                    <input type="text" class="form-control text-center" 
                                           value="${item.quantity}" readonly>
                                    <button type="button" class="btn btn-outline-secondary" 
                                            onclick="increaseQuantity(${item.id}, ${product.stock})">+</button>
                                </div>
                            </div>
                            <div class="col-auto">
                                <span class="text-danger fw-bold">¥${(product.price * item.quantity).toFixed(2)}</span>
                            </div>
                            <div class="col-auto">
                                <button class="btn btn-sm btn-light" onclick="deleteItem(${item.id})">
                                    <i class="bi bi-trash"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                `;
                
                cartItemsList.append(cartItemHtml);
            });
        }
        
        // 更新结算信息
        function updateCartSummary() {
            let selectedCount = 0;
            let totalPrice = 0;
            
            cartData.forEach(function(item) {
                if (item.checked === 1 && item.product) {
                    selectedCount += item.quantity;
                    totalPrice += item.product.price * item.quantity;
                }
            });
            
            $('#selectedCount').text(selectedCount);
            $('#totalPrice').text(totalPrice.toFixed(2));
            
            // 如果有选中的商品，启用结算按钮
            $('#checkoutBtn').prop('disabled', selectedCount === 0);
            
            // 更新全选按钮状态
            const allChecked = cartData.length > 0 && cartData.every(item => item.checked === 1);
            $('#selectAll').prop('checked', allChecked);
        }
        
        // 更新商品选中状态
        function updateItemChecked(id, checked) {
            $.ajax({
                url: '/cart/update/checked',
                type: 'POST',
                data: {
                    id: id,
                    checked: checked ? 1 : 0
                },
                success: function(res) {
                    if (res.code === 0) {
                        // 更新本地数据
                        const item = cartData.find(item => item.id === id);
                        if (item) {
                            item.checked = checked ? 1 : 0;
                            updateCartSummary();
                        }
                    } else {
                        showToast(res.msg || '操作失败', 'danger');
                        // 恢复原状态
                        $(`.cart-item[data-id="${id}"] .item-checkbox`).prop('checked', !checked);
                    }
                },
                error: function() {
                    showToast('请求失败，请重试', 'danger');
                    // 恢复原状态
                    $(`.cart-item[data-id="${id}"] .item-checkbox`).prop('checked', !checked);
                }
            });
        }
        
        // 更新所有商品选中状态
        function updateAllItemsChecked(checked) {
            $.ajax({
                url: '/cart/select/all',
                type: 'POST',
                data: {
                    checked: checked ? 1 : 0
                },
                success: function(res) {
                    if (res.code === 0) {
                        // 更新本地数据
                        cartData.forEach(item => {
                            item.checked = checked ? 1 : 0;
                        });
                        updateCartSummary();
                    } else {
                        showToast(res.msg || '操作失败', 'danger');
                        // 恢复原状态
                        $('#selectAll').prop('checked', !checked);
                    }
                },
                error: function() {
                    showToast('请求失败，请重试', 'danger');
                    // 恢复原状态
                    $('#selectAll').prop('checked', !checked);
                }
            });
        }
        
        // 减少商品数量
        function decreaseQuantity(id) {
            const item = cartData.find(item => item.id === id);
            if (!item || item.quantity <= 1) return;
            
            updateQuantity(id, item.quantity - 1);
        }
        
        // 增加商品数量
        function increaseQuantity(id, stock) {
            const item = cartData.find(item => item.id === id);
            if (!item || item.quantity >= stock) {
                showToast('库存不足', 'danger');
                return;
            }
            
            updateQuantity(id, item.quantity + 1);
        }
        
        // 更新商品数量
        function updateQuantity(id, quantity) {
            $.ajax({
                url: '/api/cart/update/quantity',
                type: 'POST',
                data: {
                    id: id,
                    quantity: quantity
                },
                success: function(res) {
                    if (res.code === 0) {
                        // 更新本地数据和UI
                        const item = cartData.find(item => item.id === id);
                        if (item) {
                            item.quantity = quantity;
                            $(`.cart-item[data-id="${id}"] input[type="text"]`).val(quantity);
                            const subtotal = item.product.price * quantity;
                            $(`.cart-item[data-id="${id}"] .text-danger.fw-bold`).text(`¥${subtotal.toFixed(2)}`);
                            updateCartSummary();
                        }
                    } else {
                        showToast(res.msg || '操作失败', 'danger');
                    }
                },
                error: function() {
                    showToast('请求失败，请重试', 'danger');
                }
            });
        }
        
        // 删除商品
        function deleteItem(id) {
            if (confirm('确定要从购物车中删除此商品吗？')) {
                $.ajax({
                    url: '/api/cart/delete',
                    type: 'POST',
                    data: {
                        id: id
                    },
                    success: function(res) {
                        if (res.code === 0) {
                            // 删除本地数据和UI
                            cartData = cartData.filter(item => item.id !== id);
                            $(`.cart-item[data-id="${id}"]`).fadeOut(300, function() {
                                $(this).remove();
                                if (cartData.length === 0) {
                                    $('#emptyCart').show();
                                }
                                updateCartSummary();
                            });
                            showToast('商品已从购物车中移除', 'success');
                        } else {
                            showToast(res.msg || '删除失败', 'danger');
                        }
                    },
                    error: function() {
                        showToast('请求失败，请重试', 'danger');
                    }
                });
            }
        }
        
        // 删除选中的商品
        function deleteSelected() {
            const selectedItems = cartData.filter(item => item.checked === 1);
            if (selectedItems.length === 0) {
                showToast('请先选择要删除的商品', 'warning');
                return;
            }
            
            if (confirm(`确定要删除选中的 ${selectedItems.length} 件商品吗？`)) {
                const deletePromises = selectedItems.map(item => {
                    return new Promise((resolve, reject) => {
                        $.ajax({
                            url: '/api/cart/delete',
                            type: 'POST',
                            data: {
                                id: item.id
                            },
                            success: function(res) {
                                if (res.code === 0) {
                                    resolve(item.id);
                                } else {
                                    reject();
                                }
                            },
                            error: function() {
                                reject();
                            }
                        });
                    });
                });
                
                Promise.all(deletePromises.map(p => p.catch(() => null)))
                    .then(deletedIds => {
                        // 过滤掉null值
                        const successIds = deletedIds.filter(id => id !== null);
                        if (successIds.length > 0) {
                            // 更新本地数据和UI
                            cartData = cartData.filter(item => !successIds.includes(item.id));
                            successIds.forEach(id => {
                                $(`.cart-item[data-id="${id}"]`).fadeOut(300, function() {
                                    $(this).remove();
                                });
                            });
                            
                            if (cartData.length === 0) {
                                $('#emptyCart').show();
                            }
                            
                            updateCartSummary();
                            showToast(`已删除 ${successIds.length} 件商品`, 'success');
                        }
                    });
            }
        }
        
        // 结算
        function checkout() {
            const selectedItems = cartData.filter(item => item.checked === 1);
            if (selectedItems.length === 0) {
                showToast('请先选择要结算的商品', 'warning');
                return;
            }
            
            // 跳转到订单确认页面
            window.location.href = '/order/confirm';
        }
        
        function showToast(message, type) {
            const toastContainer = document.querySelector('.toast-container');
            if (!toastContainer) return;
            
            const toast = document.createElement('div');
            toast.className = `toast align-items-center text-white bg-${type} border-0`;
            toast.setAttribute('role', 'alert');
            toast.setAttribute('aria-live', 'assertive');
            toast.setAttribute('aria-atomic', 'true');
            
            toast.innerHTML = `
                <div class="d-flex">
                    <div class="toast-body">
                        <i class="bi bi-${type === 'success' ? 'check-circle' : type === 'warning' ? 'exclamation-triangle' : 'exclamation-circle'} me-2"></i>
                        ${message}
                    </div>
                    <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
                </div>
            `;
            
            toastContainer.appendChild(toast);
            const bsToast = new bootstrap.Toast(toast, {
                autohide: true,
                delay: 3000
            });
            
            bsToast.show();
            
            // 自动移除toast元素
            toast.addEventListener('hidden.bs.toast', function () {
                toast.remove();
            });
        }
    </script>
</body>
</html> 